﻿using coremvcdemo.Helper;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;

namespace coremvcdemo.Code
{
    public class LoginFilter : ActionFilterAttribute, IExceptionFilter
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var noNeedCheck = false;
            if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor)
            {
                noNeedCheck = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
                  .Any(a => a.GetType().Equals(typeof(NoSignAttribute)));
            }
            if (noNeedCheck) return;
            var code = context.HttpContext.Session.GetString("code");
            if (code == null)
            {
                throw new Exception("NoLogin");
            }
        }
        public void OnException(ExceptionContext context)
        {
            throw new Exception(context.Exception.Message);
        }
        /// <summary>
        /// 不需要登陆的地方加个这个空的拦截器
        /// </summary>
        public class NoSignAttribute : ActionFilterAttribute { }
    }
}
